package com.hskn.hss.module.alarmsheshi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.controller.BaseController;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AbnormalResult;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmperson.entity.AlarmPerson;
import com.hskn.hss.module.alarmsheshi.entity.AlarmSheshi;
import com.hskn.hss.module.alarmsheshi.entity.AlarmSheshiCharts;
import com.hskn.hss.module.alarmsheshi.mapper.AlarmSheshiMapper;
import com.hskn.hss.module.alarmsheshi.service.IAlarmSheshiService;
import com.hskn.hss.module.alarmsheshi.vo.AlarmSheshiTableDetailVO;
import com.hskn.hss.module.alarmsheshi.vo.AlarmSheshiVO;
import com.hskn.hss.module.common.to.OilNumTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.dturecord.entity.DtuRecord;
import com.hskn.hss.module.dturecord.mapper.DtuRecordMapper;
import com.hskn.hss.module.kfkdeal.service.impl.KfkHandleServiceImpl;
import com.hskn.hss.module.tlempsalary.mapper.TlEmpSalaryMapper;
import com.hskn.hss.module.tlequip.entity.TlEquip;
import com.hskn.hss.module.tlequip.service.ITlEquipService;
import com.hskn.hss.module.tlfacilities.entity.TlFacilities;
import com.hskn.hss.module.tlfacilities.service.ITlFacilitiesService;
import com.hskn.hss.module.tlthreshold.entity.TlThreshold;
import com.hskn.hss.module.tlthreshold.service.ITlThresholdService;
import com.hskn.hss.utils.PerformanceMonitor.PerformanceMonitor;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-21
 */
@Api(tags = {"-tl_alarm_sheshi"}, description = "设施报警")
@Slf4j
@RestController
@RequestMapping("/hss/alarmsheshi")
public class AlarmSheshiController extends BaseController {

    @Autowired
    private IAlarmSheshiService alarmSheshiService;
    @Autowired
    ISysDepartService departService;
    @Autowired
    ITlFacilitiesService tlFacilitiesService;
    @Autowired
    ITlEquipService tlEquipService;
    @Resource
    DtuRecordMapper dtuRecordMapper;
    @Resource
    private AlarmSheshiMapper alarmSheshiMapper;
    @Autowired
    private ITlThresholdService tlThresholdService;
    @Autowired
    private KfkHandleServiceImpl kfkHandleServiceImpl;

    @RequestMapping(value = "list", method = RequestMethod.POST)
    public AjaxResult<Object> list(HttpServletRequest request) {
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject list = alarmSheshiService.mList(entity, params);
            return AjaxResult.success(list);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @ApiOperation(value = "当天设施异常接口", notes = "当天车辆异常")
    @RequestMapping(value = "abnormal", method = RequestMethod.POST)
    public AjaxResult<Object> abnormal(HttpServletRequest request) {
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = alarmSheshiService.getAbnormal();
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "alarm_sheshi", idKey = "alarmSheshiIds", bean = AlarmSheshi.class, beanMapper = AlarmSheshiMapper.class, names = "sheshiName")
    @ApiOperation(value = "批量处理接口", notes = "批量处理")
    @RequestMapping(value = "deal", method = RequestMethod.POST)
    public AjaxResult<Object> deal(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            alarmSheshiService.deal(params);
            return AjaxResult.success("处理成功");
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "selectAlarmSheshiForCharts", method = RequestMethod.POST)
    public AjaxResult<Object> selectAlarmSheshiForCharts(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            AlarmSheshi alarmSheshi=new AlarmSheshi();
            if(params!=null){
                alarmSheshi=JSONObject.parseObject(params.toJSONString(),AlarmSheshi.class);
            }
            if(StringUtils.isNotEmpty(alarmSheshi.getDepId())){
                List<String> depIds=departService.getChildIdsByIId(alarmSheshi.getDepId());
                alarmSheshi.setDepIds(depIds);
            }
            return AjaxResult.success( alarmSheshiService.selectAlarmSheshiForCharts(alarmSheshi));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @RequestMapping(value = "selectAlarmSheshiForChartsTable", method = RequestMethod.POST)
    public AjaxResult<Object> selectAlarmSheshiForChartsTable(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            AlarmSheshi alarmSheshi=new AlarmSheshi();
            if(params!=null){
                alarmSheshi=JSONObject.parseObject(params.toJSONString(),AlarmSheshi.class);
            }
            if(StringUtils.isNotEmpty(alarmSheshi.getDepId())){
                List<String> depIds=departService.getChildIdsByIId(alarmSheshi.getDepId());
                alarmSheshi.setDepIds(depIds);
            }
            if(params!=null&&params.containsKey("pageNum")&&params.containsKey("pageSize")){
                startPage(params.getInteger("pageNum"),params.getInteger("pageSize"));
            }else{
                return AjaxResult.fail("pageNum，pageSize不能为空");
            }
            return AjaxResult.success( Tools.getDataTable(alarmSheshiService.selectAlarmSheshiForChartsTable(alarmSheshi)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }


    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            QueryWrapper<AlarmSheshi> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().orderByDesc(AlarmSheshi::getCreateTime);
            List<String> ids= Arrays.asList(params.getString("ids").split(","));
            if(StringUtils.isNotEmpty(ids) && !(ids.size() ==1 && StringUtils.isEmpty(String.valueOf(ids.get(0))))){
                queryWrapper.lambda().in(AlarmSheshi::getAlarmSheshiId,ids);
            }
            String alarmSheshiId = params.getString("alarmSheshiId");
            if (StringUtils.isNotEmpty(alarmSheshiId)) {
                queryWrapper.lambda().eq(AlarmSheshi::getAlarmSheshiId,alarmSheshiId);
            }
            String sheshiId = params.getString("sheshiId");
            if (StringUtils.isNotEmpty(sheshiId)) {
                queryWrapper.lambda().eq(AlarmSheshi::getSheshiId,sheshiId);
            }
            String alarmTypeId = params.getString("alarmTypeId");
            if (StringUtils.isNotEmpty(alarmTypeId)) {
                queryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeId,alarmTypeId);
            }
            String alarmTypeName = params.getString("alarmTypeName");
            if (StringUtils.isNotEmpty(alarmTypeName)) {
                queryWrapper.lambda().eq(AlarmSheshi::getAlarmTypeName,alarmTypeName);
            }
            String startDate = params.getString("startDate");
            String endDate = params.getString("endDate");
            if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
                queryWrapper.lambda().between(AlarmSheshi::getAlarmTime,startDate + " 00:00:00",endDate + " 23:59:59");
            }
            String facilitiesTypeId = params.getString("facilitiesTypeId");
            if (StringUtils.isNotEmpty(facilitiesTypeId)) {
                queryWrapper.lambda().eq(AlarmSheshi::getFacltypeid,facilitiesTypeId);
            }
            String facilitiesTypeItemsId = params.getString("facilitiesTypeItemsId");
            if (StringUtils.isNotEmpty(facilitiesTypeItemsId)) {
                queryWrapper.lambda().eq(AlarmSheshi::getFacltypeitemid,facilitiesTypeItemsId);
            }
            String sheShiNames = params.getString("sheShiName");
            if (StringUtils.isNotEmpty(sheShiNames)) {
                sheShiNames = "('" + sheShiNames.replace(",", "','") + "')";
                queryWrapper.lambda().in(AlarmSheshi::getSheshiName,sheShiNames);
            }
            List<AlarmSheshi> alarmSheshis = alarmSheshiMapper.selectList(queryWrapper);

            //工具类实例化
            ExcelUtil<AlarmSheshiVO> util = new ExcelUtil<>(AlarmSheshiVO.class);
            //数据载体转换
            List<AlarmSheshiVO> alarmSheshiVO=JSONObject.parseArray(JSONObject.toJSONString(alarmSheshis),AlarmSheshiVO.class);
            //导出
            return util.exportExcel(alarmSheshiVO,"设施报警");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }
    }


    @PostMapping("reportForExcelExport")
    public com.hskn.hss.core.domain.AjaxResult reportForExcelExport(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            AlarmSheshi alarmSheshi=new AlarmSheshi();
            if(params!=null){
                alarmSheshi=JSONObject.parseObject(params.toJSONString(),AlarmSheshi.class);
            }
            if(alarmSheshi.getSheshiIds() == null ||alarmSheshi.getSheshiIds().size()>0){

            List<AlarmSheshiCharts> alarmSheshiChartsList = alarmSheshiService.selectAlarmSheshiForChartsTable(alarmSheshi);
            //工具类实例化
            ExcelUtil<AlarmSheshiCharts> util = new ExcelUtil<>(AlarmSheshiCharts.class);
            return util.exportExcel(alarmSheshiChartsList,"sheshiAlarmReport");
            }else{
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return com.hskn.hss.core.domain.AjaxResult.error("操作失败");
        }
    }

    /**
     * 报警统计表明细
     * @param request
     * @return
     */
    @RequestMapping(value = "selectAlarmSheshiForTableDetail", method = RequestMethod.POST)
    public AjaxResult<Object> selectAlarmSheshiForTableDetail(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            AlarmSheshi alarmSheshi=new AlarmSheshi();
            if(params!=null){
                alarmSheshi=JSONObject.parseObject(params.toJSONString(),AlarmSheshi.class);
            }
            return AjaxResult.success(alarmSheshiService.selectAlarmSheshiForTableDetail(alarmSheshi));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    /**
     * 报警统计表明细导出
     * @param request
     * @return
     */
    @RequestMapping(value = "reportForExcelExportDetail", method = RequestMethod.POST)
    public com.hskn.hss.core.domain.AjaxResult reportForExcelExportDetail(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            AlarmSheshi alarmSheshi=new AlarmSheshi();
            if(params!=null){
                alarmSheshi=JSONObject.parseObject(params.toJSONString(),AlarmSheshi.class);
            }
            if(alarmSheshi.getIds() == null || alarmSheshi.getIds().size()>0){
                List<AlarmSheshiTableDetailVO> alarmSheshiTableDetailVOList=alarmSheshiService.getAlarmSheshiTableDetailVOS(alarmSheshi);
                ExcelUtil<AlarmSheshiTableDetailVO> util = new ExcelUtil<>(AlarmSheshiTableDetailVO.class);
                return util.exportExcel(alarmSheshiTableDetailVOList,"reportDetailSheshiAlarm");
            }else{
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return com.hskn.hss.core.domain.AjaxResult.error("操作失败");
        }
    }

    /**
     * 修复设施报警数据
     * @param oilNumTO
     */
    @PostMapping("/updateAlarmSheshi")
    public void updateAlarmSheshi(@RequestBody @Validated OilNumTO oilNumTO) {
        PerformanceMonitor.begin("-----------------------修复设施报警数据执行时间------------------~");
        //车辆轨迹queryWrapper
        QueryWrapper<DtuRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(DtuRecord::getTimestamp);
        queryWrapper.lambda().ge(DtuRecord::getTimestamp, oilNumTO.getStartTime());
        queryWrapper.lambda().le(DtuRecord::getTimestamp, oilNumTO.getEndTime());
        List<DtuRecord> dtuRecordList = dtuRecordMapper.selectList(queryWrapper);

        Map<String, TlFacilities> facilitiesMap = tlFacilitiesService.getFacMap(new QueryWrapper<>());
        Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
        Map<String, TlEquip> tlEquipMapByEquipcodeMap = tlEquipService.getTlEquipMapByEquipcodeMap(new QueryWrapper<>());

        Map<String, List<DtuRecord>> dtuRecordMap = dtuRecordList.stream().collect(Collectors.groupingBy(DtuRecord::getEqpnum));
        dtuRecordMap.keySet().forEach(eqpnum->{
            TlEquip tlEquip = tlEquipMapByEquipcodeMap.get(eqpnum);
            if (Objects.isNull(tlEquip)){
                return;
            }
            TlFacilities tlFacilities = facilitiesMap.get(tlEquip.getBindobjid());
            if (Objects.isNull(tlFacilities)){
                return;
            }
            if (StringUtils.isNotEmpty(tlFacilities.getFacldeptid())){
                SysDepart sysDepart = departMap.get(tlFacilities.getFacldeptid());
                if (Objects.nonNull(sysDepart) && StringUtils.isNotEmpty(sysDepart.getDepartName())){
                    tlFacilities.setFacldeptname(sysDepart.getDepartName());
                }
            }

            List<DtuRecord> dtuRecords = dtuRecordMap.get(eqpnum);

            if (Objects.nonNull(dtuRecords) && dtuRecords.size() > 0){
                //按照设备上传定位时间正序排序
                Collections.sort(dtuRecords, (o1, o2) -> {
                    Date d1 = o1.getTimestamp();
                    Date d2 = o2.getTimestamp();
                    return d1.compareTo(d2);
                });
            }

//                List<TlThreshold> tlThresholdList = tlThresholdService.getCarThresholdsFromRedis(tlFacilities.getId());
//                for (TlThreshold tlThreshold : tlThresholdList) {
                for (int i = 0; i < dtuRecords.size(); i++) {
                    //上传时间
                    Date locationDate = dtuRecords.get(i).getTimestamp();
                    //格式化
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sDate = sdf.format(locationDate);

                    TlEquip equip = tlEquipMapByEquipcodeMap.get(dtuRecords.get(i).getEqpnum());
                    if (null == equip) {
                        return;
                    }
                    TlFacilities facilities = facilitiesMap.get(equip.getBindobjid());
                    if (null == facilities) {
                        return;
                    }
                    String bjName;
                    String name;
                    if ("smoke".equals(dtuRecords.get(i).getCategory())) {
                        bjName = "烟雾报警";
                        name = "ywnd";
                    } else if ("humidity".equals(dtuRecords.get(i).getCategory())) {
                        bjName = "硫化氢报警";
                        name = "lhqnd";
                    } else if ("ammonia".equals(dtuRecords.get(i).getCategory())) {
                        bjName = "氨气报警";
                        name = "aqnd";
                    } else {
                        return;
                    }
                    TlThreshold threshold = tlThresholdService.getCarOneThresholdFromRedis(facilities.getId(), bjName);
                    if (null == threshold) {
                        return;
                    }
                    if (StringUtils.isNotEmpty(threshold.getStatus()) && "0".equals(threshold.getStatus())) {
                        return;
                    }
                    JSONObject jsonObject = JSONObject.parseObject(threshold.getThreshold());
                    BigDecimal num = new BigDecimal(String.valueOf(jsonObject.get(name)));
                    BigDecimal valueResult = new BigDecimal(String.valueOf(dtuRecords.get(i).getValue()));
                    if (StringUtils.isEmpty(valueResult)) {
                        valueResult = BigDecimal.ZERO;
                    }
                    if (Objects.nonNull(num) && num.compareTo(valueResult) <= 0) {
                        if ("烟雾报警".equals(bjName)) {
                            if ("0".equals(threshold.getStatus())) {
                                return;
                            }
                        } else if ("硫化氢报警".equals(bjName)) {
                            if ("0".equals(threshold.getStatus())) {
                                return;
                            }
                        } else if ("氨气报警".equals(bjName)) {
                            if ("0".equals(threshold.getStatus())) {
                                return;
                            }
                        }
                        AbnormalResult abnormalResult = kfkHandleServiceImpl.saveAlarmSheshi(equip, facilities, threshold, locationDate, locationDate, new BigDecimal(String.valueOf(valueResult)), String.valueOf(dtuRecords.get(i).getCategory()));
                    }
                }
//                }
//            }
        });
        PerformanceMonitor.end();
    }

}

